<template>
  <div class="dev-plan-page" v-loading="loading">
    <section class="header">
      <div>
        <h1>开发计划</h1>
        <p>跟踪阶段目标、关键任务与风险提醒，支撑团队协作推进。</p>
      </div>
    </section>

    <section class="overview">
      <el-card v-for="item in overviewCards" :key="item.label" class="overview-card">
        <div class="card-label">{{ item.label }}</div>
        <div class="card-value">{{ item.value }}</div>
        <el-progress
          v-if="item.progress !== undefined"
          :percentage="item.progress"
          :status="item.progress === 100 ? 'success' : 'active'"
          :stroke-width="6"
          striped
        />
      </el-card>
    </section>

    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="关键任务" name="tasks">
        <section class="tasks">
          <div class="section-header">
            <div class="section-title">
              <h2>关键任务</h2>
            </div>
            <el-button type="primary" @click="openTaskDialog()">新增任务</el-button>
          </div>
          <el-table :data="tasks" border row-key="id" :default-expand-all="false">
            <el-table-column type="expand">
              <template #default="{ row }">
                <div class="task-stages-container">
                  <div class="stages-header">
                    <h3>阶段进度</h3>
                    <el-button type="primary" size="small" @click="openStageDialog(row)">新增阶段</el-button>
                  </div>
                  <el-table
                    v-if="row.stages && row.stages.length"
                    :data="row.stages"
                    border
                    size="small"
                    style="margin-top: 16px"
                    row-key="id"
                  >
                    <el-table-column type="index" label="序号" width="60" :index="(index) => index + 1" />
                    <el-table-column prop="name" label="阶段" min-width="150" show-overflow-tooltip />
                    <el-table-column label="完成状态" width="120">
                      <template #default="{ row: stage }">
                        <el-checkbox v-model="stage.completed" @change="toggleStageCompleted(row, stage)">
                          {{ stage.completed ? '已完成' : '未完成' }}
                        </el-checkbox>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                      <template #default="{ row: stage }">
                        <el-button type="primary" link size="small" @click="openStageDialog(row, stage)">编辑</el-button>
                        <el-button type="danger" link size="small" @click="confirmDeleteStage(row, stage)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty v-else description="暂无阶段，请添加" :image-size="80" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="优先级" width="100" align="center">
              <template #default="{ row }">
                {{ row.priority !== undefined && row.priority !== null ? row.priority : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="任务" min-width="200" show-overflow-tooltip />
            <el-table-column prop="due" label="截止日期" width="140" />
            <el-table-column label="进度" width="200">
              <template #default="{ row }">
                <el-progress :percentage="calculateTaskProgress(row)" :status="calculateTaskProgress(row) === 100 ? 'success' : undefined" />
              </template>
            </el-table-column>
            <el-table-column label="状态" width="140">
              <template #default="{ row }">
                <el-tag :type="statusTypeMap[row.status]">{{ statusLabelMap[row.status] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="risk" label="风险/备注" min-width="220" show-overflow-tooltip />
            <el-table-column label="操作" width="240">
              <template #default="{ row }">
                <el-button type="primary" link @click="openTaskDialog(row)">编辑</el-button>
                <el-button type="success" link @click="confirmArchiveTask(row)">归档</el-button>
                <el-button type="danger" link @click="confirmDeleteTask(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </section>
      </el-tab-pane>
      <el-tab-pane label="归档库" name="archived">
        <section class="archived-tasks">
          <div class="section-header">
            <div class="section-title">
              <h2>归档库</h2>
              <span class="hint-text">（已完成的任务记录）</span>
            </div>
          </div>
          <el-table :data="archivedTasks" border row-key="id" v-loading="archivedLoading" :default-expand-all="false">
            <el-table-column type="expand">
              <template #default="{ row }">
                <div class="task-stages-container">
                  <div class="stages-header">
                    <h3>阶段进度</h3>
                  </div>
                  <el-table
                    v-if="row.stages && row.stages.length"
                    :data="row.stages"
                    border
                    size="small"
                    style="margin-top: 16px"
                    row-key="id"
                  >
                    <el-table-column type="index" label="序号" width="60" :index="(index) => index + 1" />
                    <el-table-column prop="name" label="阶段" min-width="150" show-overflow-tooltip />
                    <el-table-column label="完成状态" width="120">
                      <template #default="{ row: stage }">
                        <el-checkbox v-model="stage.completed" disabled>
                          {{ stage.completed ? '已完成' : '未完成' }}
                        </el-checkbox>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty v-else description="暂无阶段" :image-size="80" />
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="60" :index="(index) => index + 1" />
            <el-table-column prop="name" label="任务" min-width="200" show-overflow-tooltip />
            <el-table-column prop="due" label="截止日期" width="140" />
            <el-table-column label="进度" width="200">
              <template #default="{ row }">
                <el-progress :percentage="calculateTaskProgress(row)" :status="calculateTaskProgress(row) === 100 ? 'success' : undefined" />
              </template>
            </el-table-column>
            <el-table-column label="状态" width="140">
              <template #default="{ row }">
                <el-tag :type="statusTypeMap[row.status]">{{ statusLabelMap[row.status] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="archived_at" label="归档时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.archived_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="risk" label="风险/备注" min-width="220" show-overflow-tooltip />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" link @click="confirmUnarchiveTask(row)">移出归档</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!archivedLoading && archivedTasks.length === 0" description="暂无归档任务" :image-size="80" />
        </section>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="taskDialogVisible" :title="isEditingTask ? '编辑任务' : '新增任务'" width="520px">
      <el-form ref="taskFormRef" :model="taskForm" :rules="taskRules" label-width="90px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="截止日期" prop="due">
          <el-date-picker
            v-model="taskForm.due"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="taskForm.priority" :min="0" placeholder="数字越小优先级越高" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="taskForm.status" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险备注" prop="risk">
          <el-input
            v-model="taskForm.risk"
            type="textarea"
            placeholder="风险说明或补充信息"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="taskDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="taskSubmitting" @click="submitTaskForm">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="stageDialogVisible" :title="isEditingStage ? '编辑阶段' : '新增阶段'" width="480px">
      <el-form ref="stageFormRef" :model="stageForm" :rules="stageRules" label-width="90px">
        <el-form-item label="阶段名称" prop="name">
          <el-input v-model="stageForm.name" placeholder="请输入阶段名称" />
        </el-form-item>
        <el-form-item label="完成状态" prop="completed">
          <el-checkbox v-model="stageForm.completed">已完成</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="stageDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="stageSubmitting" @click="submitStageForm">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDevelopmentPlan,
  createPlanTask,
  updatePlanTask,
  deletePlanTask,
  createTaskStage,
  updateTaskStage,
  deleteTaskStage,
  archiveTask,
  getArchivedTasks,
  unarchiveTask
} from '@/services/development-plan'

const loading = ref(false)
const tasks = ref([])
const archivedTasks = ref([])
const archivedLoading = ref(false)
const activeTab = ref('tasks')

const taskDialogVisible = ref(false)
const taskSubmitting = ref(false)
const isEditingTask = ref(false)
const editingTaskId = ref('')
const taskFormRef = ref()
const taskForm = reactive({
  name: '',
  due: '',
  status: 'progress',
  risk: '',
  priority: null
})

const stageDialogVisible = ref(false)
const stageSubmitting = ref(false)
const isEditingStage = ref(false)
const editingStageId = ref('')
const stageFormRef = ref()
const stageForm = reactive({
  name: '',
  completed: false
})

const statusTypeMap = {
  done: 'success',
  progress: 'warning',
  blocked: 'danger'
}

const statusLabelMap = {
  done: '已完成',
  progress: '进行中',
  blocked: '受阻'
}

const statusOptions = [
  { label: '进行中', value: 'progress' },
  { label: '受阻', value: 'blocked' },
  { label: '已完成', value: 'done' }
]

const completionRate = computed(() => {
  if (!tasks.value.length) return 0
  const finished = tasks.value.filter((item) => item.status === 'done').length
  return Math.round((finished / tasks.value.length) * 100)
})

const pendingTasks = computed(() => tasks.value.filter((item) => item.status !== 'done').length)

const completedTasks = computed(() => archivedTasks.value.length)

const pendingStages = computed(() => {
  return tasks.value.reduce((sum, task) => {
    return sum + (task.stages?.filter(stage => !stage.completed).length || 0)
  }, 0)
})

const completedStages = computed(() => {
  return archivedTasks.value.reduce((sum, task) => {
    return sum + (task.stages?.filter(stage => stage.completed).length || 0)
  }, 0)
})

const overviewCards = computed(() => [
  { label: '待处理任务', value: `${pendingTasks.value} 个` },
  { label: '完成任务', value: `${completedTasks.value} 个` },
  { label: '阶段总数', value: `${pendingStages.value} 个` },
  { label: '完成阶段', value: `${completedStages.value} 个` }
])

const toggleStageCompleted = async (task, stage) => {
  try {
    await updateTaskStage(task.id, stage.id, { completed: stage.completed })
    ElMessage.success(stage.completed ? '阶段已标记为完成' : '阶段已标记为未完成')
    // 阶段完成状态改变后，进度会自动根据阶段计算，无需手动更新
  } catch (error) {
    // 如果更新失败，恢复原状态
    stage.completed = !stage.completed
    const errorMsg = error?.message || error?.response?.data?.detail || '更新失败'
    ElMessage.error(errorMsg)
    console.error('更新阶段完成状态失败:', error)
  }
}

const taskRules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  due: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const stageRules = {
  name: [{ required: true, message: '请输入阶段名称', trigger: 'blur' }]
}

const resetTaskForm = () => {
  taskForm.name = ''
  taskForm.due = ''
  taskForm.status = 'progress'
  taskForm.risk = ''
  taskForm.priority = null
}

const resetStageForm = () => {
  stageForm.name = ''
  stageForm.completed = false
}

const openTaskDialog = (task) => {
  if (task) {
    isEditingTask.value = true
    editingTaskId.value = task.id
    Object.assign(taskForm, {
      name: task.name || '',
      due: task.due || '',
      status: task.status || 'progress',
      risk: task.risk || '',
      priority: task.priority !== undefined && task.priority !== null ? task.priority : null
    })
  } else {
    isEditingTask.value = false
    editingTaskId.value = ''
    resetTaskForm()
    // 自动计算优先级：当前最大优先级 + 1
    if (tasks.value.length > 0) {
      const maxPriority = Math.max(...tasks.value.map(t => t.priority !== undefined && t.priority !== null ? t.priority : 0))
      taskForm.priority = maxPriority + 1
    } else {
      taskForm.priority = 0
    }
  }
  taskDialogVisible.value = true
}

const openStageDialog = (task, stage = null) => {
  if (stage) {
    isEditingStage.value = true
    editingTaskId.value = task.id
    editingStageId.value = stage.id
    Object.assign(stageForm, {
      name: stage.name || '',
      completed: stage.completed || false
    })
  } else {
    isEditingStage.value = false
    editingTaskId.value = task.id
    editingStageId.value = ''
    resetStageForm()
  }
  stageDialogVisible.value = true
}

const fetchPlanData = async () => {
  loading.value = true
  try {
    const res = await getDevelopmentPlan()
    const data = res?.data || res
    tasks.value = Array.isArray(data.tasks) ? data.tasks : []
    tasks.value.forEach(task => {
      if (!task.stages) {
        task.stages = []
      }
      task.stages.forEach(stage => {
        if ('due' in stage) {
          delete stage.due
        }
        if (stage.completed === undefined) {
          stage.completed = false
        }
      })
    })
    if (activeTab.value === 'tasks') {
      await fetchArchivedTasks()
    }
  } catch (error) {
    const errorMsg = error?.message || error?.response?.data?.detail || '加载开发计划失败'
    ElMessage.error(errorMsg)
    console.error('加载开发计划失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchArchivedTasks = async () => {
  archivedLoading.value = true
  try {
    const res = await getArchivedTasks()
    const data = res?.data || res
    archivedTasks.value = Array.isArray(data) ? data : []
    // 确保每个任务都有 stages 数组
    archivedTasks.value.forEach(task => {
      if (!task.stages) {
        task.stages = []
      }
    })
  } catch (error) {
    const errorMsg = error?.message || error?.response?.data?.detail || '加载归档任务失败'
    ElMessage.error(errorMsg)
    console.error('加载归档任务失败:', error)
  } finally {
    archivedLoading.value = false
  }
}

const handleTabChange = (tabName) => {
  if (tabName === 'archived') {
    fetchArchivedTasks()
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return dateString
  }
}

// 计算任务进度：根据阶段动态计算
const calculateTaskProgress = (task) => {
  if (!task.stages || !task.stages.length) {
    return 0
  }
  const completedCount = task.stages.filter(stage => stage.completed).length
  return Math.round((completedCount / task.stages.length) * 100)
}

const submitTaskForm = () => {
  taskFormRef.value?.validate(async (valid) => {
    if (!valid) return
    taskSubmitting.value = true
    try {
      const payload = { ...taskForm }
      // 不发送 progress 字段，后端会根据阶段自动计算
      delete payload.progress
      // 如果 priority 为 null，不发送该字段（让后端自动设置）
      if (payload.priority === null) {
        delete payload.priority
      }
      if (isEditingTask.value) {
        await updatePlanTask(editingTaskId.value, payload)
        ElMessage.success('任务已更新')
      } else {
        await createPlanTask(payload)
        ElMessage.success('任务已创建')
      }
      taskDialogVisible.value = false
      fetchPlanData()
    } catch (error) {
      const errorMsg = error?.message || error?.response?.data?.detail || '保存失败'
      ElMessage.error(errorMsg)
      console.error('保存任务失败:', error)
    } finally {
      taskSubmitting.value = false
    }
  })
}

const submitStageForm = () => {
  stageFormRef.value?.validate(async (valid) => {
    if (!valid) return
    stageSubmitting.value = true
    try {
      const payload = { ...stageForm }
      if (isEditingStage.value) {
        await updateTaskStage(editingTaskId.value, editingStageId.value, payload)
        ElMessage.success('阶段已更新')
      } else {
        await createTaskStage(editingTaskId.value, payload)
        ElMessage.success('阶段已创建')
      }
      stageDialogVisible.value = false
      // 阶段更新后，任务的进度会自动根据阶段计算，无需手动更新
      fetchPlanData()
    } catch (error) {
      const errorMsg = error?.message || error?.response?.data?.detail || '保存失败'
      ElMessage.error(errorMsg)
      console.error('保存阶段失败:', error)
    } finally {
      stageSubmitting.value = false
    }
  })
}

const confirmDeleteTask = (task) => {
  ElMessageBox.confirm(`确定要删除任务「${task.name}」吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        await deletePlanTask(task.id)
        ElMessage.success('任务已删除')
        fetchPlanData()
      } catch (error) {
        const errorMsg = error?.message || error?.response?.data?.detail || '删除失败'
        ElMessage.error(errorMsg)
        console.error('删除任务失败:', error)
      }
    })
    .catch(() => {})
}

const confirmDeleteStage = (task, stage) => {
  ElMessageBox.confirm(`确定要删除阶段「${stage.name}」吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        await deleteTaskStage(task.id, stage.id)
        ElMessage.success('阶段已删除')
        fetchPlanData()
      } catch (error) {
        const errorMsg = error?.message || error?.response?.data?.detail || '删除失败'
        ElMessage.error(errorMsg)
        console.error('删除阶段失败:', error)
      }
    })
    .catch(() => {})
}

const confirmArchiveTask = (task) => {
  ElMessageBox.confirm(`确定要归档任务「${task.name}」吗？归档后任务将移至归档库。`, '提示', {
    type: 'info',
    confirmButtonText: '归档',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        await archiveTask(task.id)
        ElMessage.success('任务已归档')
        fetchPlanData()
        // 如果当前在归档库标签页，刷新归档列表
        if (activeTab.value === 'archived') {
          fetchArchivedTasks()
        }
      } catch (error) {
        const errorMsg = error?.message || error?.response?.data?.detail || '归档失败'
        ElMessage.error(errorMsg)
        console.error('归档任务失败:', error)
      }
    })
    .catch(() => {})
}

const confirmUnarchiveTask = (task) => {
  ElMessageBox.confirm(`确定要将任务「${task.name}」移出归档吗？`, '提示', {
    type: 'info',
    confirmButtonText: '移出',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        await unarchiveTask(task.id)
        ElMessage.success('任务已移出归档')
        fetchArchivedTasks()
        fetchPlanData()
      } catch (error) {
        const errorMsg = error?.message || error?.response?.data?.detail || '移出归档失败'
        ElMessage.error(errorMsg)
        console.error('移出归档失败:', error)
      }
    })
    .catch(() => {})
}

onMounted(() => {
  fetchPlanData()
  // 如果默认显示归档库，加载归档数据
  if (activeTab.value === 'archived') {
    fetchArchivedTasks()
  }
})
</script>

<style scoped>
.dev-plan-page {
  display: flex;
  flex-direction: column;
  gap: 24px;
  height: 100%;
  padding: 24px;
  overflow: auto;
  background: var(--el-bg-color-page);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-radius: 12px;
  background: var(--el-color-primary-light-9);
}

.header h1 {
  font-size: 24px;
  margin-bottom: 6px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}

.overview-card {
  border-radius: 12px;
}

.card-label {
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 12px;
}

.timeline,
.tasks {
  background: var(--el-bg-color);
  border-radius: 12px;
  padding: 24px;
  box-shadow: var(--el-box-shadow-light);
}

.archived-tasks {
  background: var(--el-bg-color);
  border-radius: 12px;
  padding: 24px;
  box-shadow: var(--el-box-shadow-light);
}

.hint-text {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  font-weight: normal;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-stages-container {
  padding: 16px;
  background: var(--el-bg-color-page);
}

.stages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stages-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.el-table .el-button {
  padding: 0 4px;
}

@media (max-width: 768px) {
  .dev-plan-page {
    padding: 16px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-value {
    font-size: 22px;
  }
}
</style>

